package dc.connectionmanager.network;

import java.io.*;

import dc.connectionmanager.persistance.AConnection;

public class TCPConnection extends AConnection
{
    private java.net.Socket socket;
    private int port;
    
    public TCPConnection(String nIPAdress, int nPort)
    {
        super(nIPAdress, "", "");
        this.port = nPort;
    }

    @Override
    public boolean connect()
    {
        try
        {
            this.socket = new java.net.Socket(this.ipAdress, this.port);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return false;
        }
        
        return true;
    }

    @Override
    public boolean isConnected()
    {
        return this.socket.isConnected() && !this.socket.isClosed();
    }

    @Override
    public void closeConnection()
    {
        try
        {
            this.socket.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            this.socket = null;
        }
    }

    @Override
    public Object sendCommand(String command)
    {
        this.busy = true;
        this.setLastAction();
        
        PrintWriter pw = null;
        
        BufferedReader br = null;
        InputStreamReader isr = null;
        
        try
        {
            pw = new PrintWriter(socket.getOutputStream());
            pw.println(command);
            pw.flush();
            
            isr = new InputStreamReader(socket.getInputStream());
            
            br = new BufferedReader(isr);
            
            while(!br.ready())
            {}
            
            String answer = br.readLine();

            return (Object)answer;
            
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return new Object();
        }
        finally
        {
            pw = null;
            br = null;
            isr = null;
                                
            this.busy = false;
        }
    }

    @Override
    public void sendCommandNC(String command)
    {
        this.busy = true;
        this.setLastAction();
        
        PrintWriter pw = null;
        
        try
        {
            pw = new PrintWriter(socket.getOutputStream(), true);
            pw.println(command);
            
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            pw = null;
                               
            this.busy = false;
        }
    }

}
